package OperatorStation;

// PI class to be written by you
public class PI {

  // Private attribute containing a reference to the GUI
//  private PIGUI GUI;
  // Private attribute containing a reference to the PIParameters
  // currently used
  private PIParameters p;

  // Additional attributes
	private double error,v,I,P;
	
	
  // Constructor
  public PI(String name){
  	p = new PIParameters();
  	p.K=2;//0.5->10	//2
	p.Ti=0;		//0
	p.Tr=10;	//10
	p.Beta=1;	//1
	p.H=0.1; //0.02->0.1	0.1
	p.integratorOn=false;
	setParameters(p);
//	GUI = new PIGUI(this, p, name);
	P= 1; 
	I= 0;
  
  }

  // Calculates the control signal v. Called from BeamRegul.
  public synchronized double calculateOutput(double y, double yref){
  	error=yref-y;
  	P = p.K*(p.Beta*yref-y);
  	return P+I;  
  }

  // Updates the controller state. Should use tracking-based anti-windup
  // Called from BeamRegul.
  public synchronized void updateState(double u){
  	if(p.integratorOn==true){
  		I=I+(p.K*p.H/p.Ti)*error+(p.H/p.Tr)*(u-v);
  	}
  	else{
  		I=0.0; 
  	}		
  }

  // Returns the sampling interval expressed as a long. Explicit type casting
  // needed
  public synchronized long getHMillis(){
  	return (long)(p.H*1000.0);
  
  }

  // Sets the PIParameters. Called from PIGUI. Must clone newParameters.
  public synchronized void setParameters(PIParameters newParameters){
  	p = (PIParameters)newParameters.clone();
  	if(!p.integratorOn){
  		I=0.0; 
  	}
  }
  // Sets the I-part of the controller to 0.
  // For example needed when changing controller mode.
  public synchronized void reset(){
	I=0;;
  }
  
  // Returns the current PIParameters.
  // Ska vi returnera p.clone?
  public synchronized PIParameters getParameters(){
	return p;
  }

}
